import { getMultiLang, toast,pageTo,viewModel  } from 'nc-lightapp-front';
let { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;
import requestApi, { setMetasInit } from './requestApi';
import 'ssccommon/components/globalPresetVar';
import { setTableGroupExtendCol } from 'ssccommon/components/bill';
import { beforeUpdatePage, updatePage } from 'ssccommon/utils/updatePage';
import {updataFormData, updatacardTableData} from 'ssccommon/utils/changePageData';
import getDefDataFromMeta from 'ssccommon/utils/getDefDataFromMeta';
import { getDefaultTableButtons,excludeBodyKey } from './ExpenseUtils';
import { setPageStatus } from 'ssccommon/utils/statusController';
import { tableExtendButtonClick } from "./events";
import { setButtonsVisible } from 'ssccommon/utils/buttonUtils';
import { tableButtonClick } from './events';
import { walletClick, uploadInvoiceClick, showTableAttachment } from './events/tableButtonClick';
import attachments from 'uap/common/components/getAttachmentInfo';
import { setImportConfig } from './events/afterEvent'
import  { clearPropsAboutInvoices } from './events/tableExtendButtonClick'
import { getExcelImportConfig } from './ExcelImportUtil';
import _ from 'lodash-es'

const { getAttachments, getAttachmentsInfo } = attachments;

import logs from 'ssccommon/utils/logs';
let debugLogs = new logs();

let pagecode = '';
let appcode = '';
window.presetVar = {
    ...window.presetVar,
    head: {
        head1: 'head',
        head2: ''
    },
    body: {

    },
    buttonTpl,
};

let pageButton = presetVar.pageButton;
const statusVar = presetVar.status;
let buttonTpl = '';
// let pageHashChange = null;
export default function (props) {

    window.presetVar.lsBodys = [];
    appcode = window.presetVar.appcode = props.getUrlParam("appcode") || props.getSearchParam("c") || '';
    pagecode = window.presetVar.pagecode = props.getUrlParam("pagecode") || props.getSearchParam("p") || '';
    window.presetVar.pagestatus = props.getUrlParam('status');
    window.presetVar.id = props.getUrlParam('id');
    window.presetVar.tradetype = props.getUrlParam("tradetype") || '';


    let pageStatus = window.presetVar.pagestatus;
    let _this = this;

    let createUIDomPromise = new Promise((resolve, reject) => {
        props.createUIDom({}, (data) => {
            resolve(data);
        })
    });

    let getMultiLangPromise = new Promise((resolve, reject) => {
        getMultiLang({
            moduleId: 2011,
            domainName: 'erm',
            currentLocale: 'simpchn',
            callback: (json) => {
                resolve(json);
            }
        })
    });

    console.timeEnd('业务领域执行-开始请求模板接口的耗时：');
    console.time('请求：createUIDom耗时');
    Promise.all([createUIDomPromise, getMultiLangPromise]).then((resultList) => {
        console.timeEnd('请求：createUIDom耗时');
        console.time('meta第1次设置耗时')

        let data = resultList[0];
        let json = resultList[1];
        // 全局化组织汇率类型
        let zzhllxs = resultList[0].template.head.items.find((item,index) => {
            return item.attrcode === "zzhllx.rate_category"
        })
        window.presetVar.zzhllxs = zzhllxs && zzhllxs.options
        this.multiLangJson = json;
        // let meta = metaorder(data.template);
        let meta = data.template;
        meta['invoice_Detail'] && meta['invoice_Detail'].items && meta['invoice_Detail'].items.forEach(item => {
            if(item.attrcode === 'kprq') {
                item.itemtype = 'datepicker'
              }
        })
        props.meta.setMeta(meta);
        let bodys = Object.keys(data.template.gridrelation);
        for (var i = 1; i <= bodys.length; i++) {
            window.presetVar.body["body" + i] = bodys[i - 1];
        }

        //自定义明细添加buttons
        addCustomTableButtons(data, _this);

        //自定义页签添加到createpage中，以支持公式的执行，否则在执行编辑公式时会报未知的错误
        var billinfo = {
            billtype: 'extcard',
            pagecode: "201102BCLF_C",
            headcode: "head",
            bodycode: bodys
        }
        this.props.setRelationItemBillinfo(billinfo);

        window.presetVar.lsBodys = bodys;
        window.presetVar.pageId = meta.code;

        //表体注册增行后回调afterClick事件
        const funcs = {}
        let clickedIndex = 0;
        bodys.forEach(key => {
            if(excludeBodyKey(key)){
                funcs[`${key}_Add`] = {
                    beforeClick:()=>{
                        clickedIndex = _.get(props.cardTable.getClickRowIndex(key), 'index', null)
                        return true;
                    },
                    afterClick: () => {
                        console.log(key,'页签增行后回调')
                        //回调处理表体某些字段默认值
                        setDefautValueAfterBodyAdd.call(this, this.props, key, clickedIndex)
                    }
                }
            }
            //所有页签注册票夹回调
            funcs[`${key}_wallet`] = () => {
                console.log(`${key} click 票夹`)
                walletClick.call(this, this.props, key)
            }
            //所有表体注册发票上传回调
            funcs[`${key}_upload`] = () => {
                console.log(`${key} click 发票上传`)
                uploadInvoiceClick.call(this, this.props, key)
            }
        })
        window._tableButtonsClick = funcs

        //根据页面状态，设置区域的初始渲染状态
        meta[presetVar.head.head1].status = pageStatus;
        bodys.forEach((body) => {
            if (meta[body]) {
                if (pageStatus == statusVar.add) { //cardTable新增态也要设置成edit
                    meta[body].status = statusVar.edit;
                } else {
                    meta[body].status = pageStatus;
                }
            }
        });


        buttonTpl = {
            button: (data.button == null || data.button == undefined) ? [] : data.button
        }
        let id = window.presetVar.id || this.state.billId;
        let fileman;
        id = id == "" ? 0 : id;
        fileman = json['201102BCLF-0040'];

        //修改表体扩展的按钮顺序
        buttonTpl.button.forEach((item,index) => {
            if(item.key.indexOf('_Attachment') > -1) {
                item.order = '1'
            }
            if(item.key.indexOf('_Edit') > -1) {
                item.order = '2'
            }
            if(item.key.indexOf('_Delete') > -1) {
                item.order = '3'
            }
        })
        buttonTpl.button.sort((a,b) => Number(a.order) - Number(b.order))

        console.log('button sort:',buttonTpl.button)

        if (pageStatus == statusVar.add) {
            buttonTpl.button.find((items) => {
                if (items.key == 'fileManager') {
                    items.title = fileman + ' ' + 0 + ' ';
                    return true;
                }
            });
        } else {
            getAttachments(id).then(lists => {
                this.setState({
                    groupLists: lists
                }, () => {
                    let filenum = this.state.groupLists;

                    if (filenum.length == 0) {
                        filenum = 0;
                    }
                    buttonTpl.button.find((items) => {
                        if (items.key == 'fileManager') {
                            items.title = fileman + ' ' + filenum + ' ';
                            this.props.button.setButtonTitle(items.key, items.title);
                            return true;
                        }
                    });
                })
            })
        }

        window.presetVar.buttonTpl = buttonTpl;
        // TOP 浏览态也需要操作列，页面初始化时统一加载 ADD
        props.button.hideButtonsByAreas(window.presetVar.head.head1);
        props.button.setButtons(buttonTpl.button);
        //设置表格扩展列
        setTableExtendCol.call(this, props, meta, buttonTpl.button);
        // BTM 浏览态也需要操作列，页面初始化时统一加载
        //兼容应用复制用transtype
        let transtype = "";
        if (data.context.paramMap && data.context.paramMap.transtype) {
            transtype = data.context.paramMap.transtype;
            window.presetVar.pullpagecode = !data.context.paramMap.pullpagecode ? "" : data.context.paramMap.pullpagecode;
            this.setState({ transtype_name: data.context.paramMap.transtype_name });
        }

        window.presetVar.tradetype = window.presetVar.tradetype || transtype;
        if (pageStatus == statusVar.add && !props.getUrlParam('addType') && !props.getUrlParam('copyFromBillId')) {
            let qextend = {
                transtypecode: window.presetVar.tradetype
            };
            requestApi.queryextend({
                data: qextend,
                success: (data) => {
                    let result = JSON.parse(data.data);
                    if (result.success == "true" && result.is_mactrl == 'true') {
                        pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount4Pull/card/index.html#/pull', { isfromSsc: true, pagecode: window.presetVar.pullpagecode });
                        routeChange.call(this, this.props)
                        return;
                    } else if (result.success == "false") {
                        toast({ content: result.message, color: 'warning' });
                        return;
                    }
                }
            });
        }
        loadbill.call(this, meta, null);
    }).then(() => {
        //请求附件控制状态
        requestApi.getAttachmentControlParams({
            data: { transtypecode: window.presetVar.tradetype },
            success: (data) => {
                // data.enablemodifyaccessory  审批中是否允许修改
                // data.mustuploadaccessory 是否必须上传附件
                window.presetVar.attachmentControl = {
                    modify: data.enablemodifyaccessory,
                    necessary: data.mustuploadaccessory
                }
            }
        })
    })

    /**
     * 自定义明细 按钮, 往data里写入自定义的button数据
     * @param {button:[], template:{}, context:{}} data
     */
    function addCustomTableButtons(data, that) {
        if (!data.button || !data.button.length) return
        const buttons = data.button;
        const keys = Object.keys(data.template.gridrelation);
        const excludeKeys = ['arap_bxbusitem', 'bzitem', 'other', 'zsitem', 'er_bxcontrast',
                            'er_cshare_detail', 'accrued_verify','invoice_Detail'];
        keys.forEach(key => {
            if(!excludeKeys.includes(key)) {
                //如果不在这里的都是自定义明细
                const addButtons = getDefaultTableButtons(key)
                addButtons.forEach(btn => {
                    btn.title = that.multiLangJson[btn.title];
                    buttons.push(btn);
                })
            }
        })

    }
}

/**
 * 自定义表体
 */
function extendCustomTableCol() {
    const keys = window.presetVar.commonTableCodes
    const lsBodys = window.presetVar.lsBodys
    const ret = {}
    lsBodys.forEach(key => {
        if(keys.indexOf(key) < 0) {
            ret[key] = {
                onButtonClick: tableExtendButtonClick.bind(this),
                copyRowWithoutCols: ['pk_busitem']
            }
        }
    })
    return ret;
}

/**
 * 设置表格扩展列
 */
function setTableExtendCol(props, meta, button) {
    const extendsTableCol = extendCustomTableCol.call(this)

    setTableGroupExtendCol(props, meta, button, [], {
        "arap_bxbusitem": {
            onButtonClick: tableExtendButtonClick.bind(this),
            copyRowWithoutCols: ['pk_busitem']
        },
        "bzitem": {
            onButtonClick: tableExtendButtonClick.bind(this),
            copyRowWithoutCols: ['pk_busitem']
        },
        "other": {
            onButtonClick: tableExtendButtonClick.bind(this),
            copyRowWithoutCols: ['pk_busitem']
        },
        "zsitem": {
            onButtonClick: tableExtendButtonClick.bind(this),
            copyRowWithoutCols: ['pk_busitem']
        },
        "er_bxcontrast": {
            onButtonClick: tableExtendButtonClick.bind(this),
            copyRowWithoutCols: ['pk_bxcontrast']
        },
        "er_cshare_detail": {
            onButtonClick: tableExtendButtonClick.bind(this),
            copyRowWithoutCols: ['pk_cshare_detail']
        },
        "accrued_verify": {
            onButtonClick: tableExtendButtonClick.bind(this),
            copyRowWithoutCols: ['pk_accrued_detail']
        },
        ...extendsTableCol
    });
}

function getAttachmentControl(props) {
    //请求附件控制参数
    return new Promise((resolve, reject) =>{
        requestApi.getAttachmentControlParams({
            data: { transtypecode: window.presetVar.tradetype },
            success: (data) => {
                // data.enablemodifyaccessory  审批中是否允许修改
                // data.mustuploadaccessory 是否必须上传附件
                window.presetVar.attachmentControl = {
                    modify: data.enablemodifyaccessory,
                    necessary: data.mustuploadaccessory
                }
                // let pageStatus = props.getUrlParam('status')  || 'add';
                // dataHandle.call(this, window.presetVar.reloadHead, props, pageStatus)
                resolve()
            }
        })
    })

}
async function loadbill(meta, pagestatus) {

    let props = this.props;
    await getAttachmentControl(props)

    let pageStatus = (pagestatus == null ? props.getUrlParam('status') : pagestatus) || 'add';
    let billdata = setDefData.call(this, meta);
    if (billdata == false) {
        return;
    }
    let userjson = { "pagecode": pagecode, "appcode": appcode };
    let _this = this;
    billdata.userjson = JSON.stringify(userjson);
    let redata = window.presetVar.redata == '' ? "Y" : window.presetVar.redata;
    if (/**pageStatus == statusVar.edit ||***/ pageStatus == statusVar.browse) {
        //redata不需要重新加载单据信息
        if (redata == "N" && pagestatus) {
            // TOP 性能优化，增加统一刷新方法 chengwbc ADD
            beforeUpdatePage(props);
            // BTM 性能优化，增加统一刷新方法
            // TOP 性能优化，保存后不需要setMeta chengwbc MOD
            // render.call(this, meta,window.presetVar.buttonTpl.button,pageStatus);
            render.call(this, meta, window.presetVar.buttonTpl.button, pageStatus, false);
            // BTM 性能优化，保存后不需要setMeta
            dataHandle.call(this,window.presetVar.reloadHead, props, pageStatus)
            // TOP 性能优化，增加统一刷新方法 chengwbc ADD
            updatePage(props, 'head', window.presetVar.lsBodys);
            // BTM 性能优化，增加统一刷新方法
            return;
        }
        render.call(this, meta, buttonTpl, pagestatus, true);
        let viewbilldata = {};
        viewbilldata.openbillid = props.getUrlParam("id") || props.getUrlParam("billid");
        viewbilldata.tradetype = window.presetVar.tradetype;
        viewbilldata.uid = getCookie("userid");//"1001Z3100000000000AE";这里以后从session中获取
        //取报销标准需要用到
        viewbilldata.templateid = meta.pageid;
        viewbilldata.pagecode = pagecode;
        viewbilldata.appcode = appcode;
        requestApi.viewBill({
            data: viewbilldata,
            success: (data) => {
                // TOP 性能优化，增加统一刷新方法 chengwbc ADD
                beforeUpdatePage(props);
                // BTM 性能优化，增加统一刷新方法
                props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                window.presetVar.reloadHead = data.head[presetVar.head.head1];
                window.presetVar.bodyAllValues = data.bodys
                // TOP 性能优化，先设置页面状态后加载数据 chengwbc MOVE:1818181430

                // BTM 性能优化，先设置页面状态后加载数据
                dataHandle.call(this,window.presetVar.reloadHead, props, pageStatus);
                setbilldata(this, props, data.head[presetVar.head.head1].rows[0].values);

                setPageStatus(props, meta, ['head'], window.presetVar.lsBodys, 'browse');
                // BTM 整体设置页面状态
                let iscostshare = props.form.getFormItemsValue("head", ['iscostshare']) == null ? "" : props.form.getFormItemsValue("head", ['iscostshare'])[0].value
                if (iscostshare == true) {
                    props.form.setFormItemsDisabled("head",{'fydwbm_v':true});
                    setImportConfig(_this);//设置导入按钮
                    _this.setState({hideTables:[]})
                } else {
                    _this.setState({ hideTables: ['er_cshare_detail'] })
                }
                requestApi.setMetasInit(meta, props, data);
                props.meta.setMeta(meta);
                if (data.userjson && JSON.parse(data.userjson)) {
                    let djlx = JSON.parse(data.userjson);
                    if (djlx && djlx.ISCONTRAST && djlx.jkyjye && djlx.jkyjye > 0) {//是否冲借款
                        window.presetVar["ISCONTRAST"] = djlx.ISCONTRAST;
                    }
                    if (djlx && djlx.IS_MACTRL) {//是否冲借款
                        window.presetVar["IS_MACTRL"] = djlx.IS_MACTRL;
                    }
                    if(JSON.parse(data.userjson).invoiceToBx){
                        window.presetVar.invoiceToBx = JSON.parse(data.userjson).invoiceToBx
                        window.presetVar.bxToInvoice = JSON.parse(data.userjson).bxToInvoice
                    }
                }

                //设置表体数据
                window.presetVar.lsBodys.forEach((body) => {
                    if (data.bodys[body]) {
                        props.cardTable.setTableData(body, data.bodys[body]);
                    }
                });
                updatePage(props, 'head', window.presetVar.lsBodys);

            }
        });
        //by houyb 20190830 获取控制项
        //loadReimsrc.call(this,meta,billdata,pagestatus);
    }
    //新增和拉单新增加载需要loaddata
    else if (pageStatus == statusVar.add) {
        let addtype = props.getUrlParam('addType');
        let copyFromBillId = props.getUrlParam('copyFromBillId');
        if (addtype == "pull") {
            let transfervalue = props.transferTable.getTransferTableSelectedId("head");

            userjson["addType"] = addtype;
            userjson["pulldata"] = transfervalue;
            billdata.userjson = JSON.stringify(userjson);

        }
        if (copyFromBillId) {
            let param = {};
            param.copyFromBillId = copyFromBillId;
            param.tradetype = window.presetVar.tradetype;
            param.pagecode = pagecode;
            param.appcode = appcode;
            requestApi.copyBill({
                data: param,
                success: (data) => {
                    beforeUpdatePage(props);
                    props.form.EmptyAllFormValue(presetVar.head.head1);
                    props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                    //设置表体数据
                    window.presetVar.reloadHead = data.head[presetVar.head.head1]
                    Object.values(presetVar.body).forEach((body) => {
                        if (data.bodys[body]) {
                            props.cardTable.setTableData(body, data.bodys[body]);
                            props.cardTable.setStatus(body, "edit");
                        } else {
                            props.cardTable.setTableData(body, { rows: [] });
                        }
                    });
                    requestApi.setMetasInit(meta, props, data);

                    render.call(this, meta, buttonTpl, pagestatus);
                    dataHandle.call(this, window.presetVar.reloadHead, props, pageStatus);
                    //设置页面分摊不可编辑项，收款对象相关不可编辑项，组织本币汇率不可编辑
                    setbilldata(_this, props, data.head[presetVar.head.head1].rows[0].values);
                    this.setState({billId : data.head[presetVar.head.head1].rows[0].values.pk_jkbx.value});//复制后需要将这个变量更新，不然会影像后续的联查功能

                    const headData = data.head[presetVar.head.head1]
                    requestApi.getAttachmentControlParams({
                        data: { transtypecode: window.presetVar.tradetype },
                        success: (data) => {
                            // data.enablemodifyaccessory  审批中是否允许修改
                            // data.mustuploadaccessory 是否必须上传附件
                            window.presetVar.attachmentControl = {
                                modify: data.enablemodifyaccessory,
                                necessary: data.mustuploadaccessory
                            }
                            dataHandle.call(this, headData, props);
                        }
                    })
                }
            });
            // TOP 门户复制的单据打不开 chengwbc ADD
            props.meta.setMeta(meta);
            // BTM 门户复制的单据打不开
        } else {
            initData.call(this, meta, billdata, pageStatus);
        }
    }
    //修改更新页面状态即可，复制是需要重新加载数据
    else {

        if (props.getUrlParam("id") || props.getUrlParam("billid")) {
            if (redata == "N" && pagestatus) {
                render.call(this, meta, window.presetVar.buttonTpl.button, pageStatus);
                dataHandle.call(this, window.presetVar.reloadHead, props, pageStatus);
                return;
            }
            let billdata = {};
            billdata.openbillid = props.getUrlParam("id") || props.getUrlParam("billid");
            billdata.tradetype = window.presetVar.tradetype;
            billdata.uid = getCookie("userid");//这里以后从session中获取
            billdata.templateid = meta.pageid;
            billdata.pagecode = pagecode;
            billdata.appcode = appcode;
            requestApi.viewBill({
                data: billdata,
                meta,
                props,
                success: (data) => {
                    beforeUpdatePage(props);
                    if (data.userjson && JSON.parse(data.userjson)) {
                        let djlx = JSON.parse(data.userjson);
                        if (djlx && djlx.ISCONTRAST && djlx.ISCONTRAST == "Y" && djlx.jkyjye && djlx.jkyjye > 0) {//是否冲借款
                            window.presetVar["ISCONTRAST"] = djlx.ISCONTRAST;
                        }
                        if (djlx && djlx.IS_MACTRL) {//是否冲借款
                            window.presetVar["IS_MACTRL"] = djlx.IS_MACTRL;
                        }
                    }
                    props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                    window.presetVar.reloadHead = data.head[presetVar.head.head1];
                    //设置表体数据
                    Object.values(presetVar.body).forEach((body) => {
                        if (data.bodys[body]) {
                            debugLogs.timeStart('setTableData_' + body);
                            props.cardTable.setTableData(body, data.bodys[body]);
                            debugLogs.timeEnd('setTableData_' + body);
                        }
                    });
                    render.call(this, meta, window.presetVar.buttonTpl.button, pageStatus);
                    dataHandle.call(this, window.presetVar.reloadHead, props, pageStatus)
                    setbilldata(_this, props, data.head[presetVar.head.head1].rows[0].values);
                    debugLogs.timeStart('viewBill');
                }
            });
            // TOP 编辑态单据刷新页面报错 chengwbc ADD
            props.meta.setMeta(meta);
            // BTM 编辑态单据刷新页面报错
        }
    }
}
function setbilldata(_this, props, headData, useUpdatePage) {

    let {paytarget, isexpamt, iscostshare, bbhl:org_currinfo,bzbm} = headData;
    let disabledObj = {};
    let visibleObj = {}
    // BTM 性能优化，增加统一刷新方法
    paytarget = paytarget.value//收款对象
    if(props.form.getFormItemsVisible('head', 'paytarget')) { //如果收款对象放出来才走这里面的逻辑
        if (paytarget == "0") {
            disabledObj = {'hbbm': true,'hbbm_v': true, 'customer': true, 'customer_v': true,"custaccount": true, 'receiver': false, 'freecust': true }
        } else if (paytarget == "1") {
            disabledObj = {'receiver': true, 'customer': true,'customer_v': true, 'hbbm': false,'hbbm_v': false, 'custaccount': false, 'freecust': false }
        } else if (paytarget == "2") {
            disabledObj = {'hbbm': true, 'hbbm_v': true,'receiver': true, 'customer': false, 'customer_v': false, 'custaccount': false, 'freecust': true}
        }
    }
    isexpamt = isexpamt.value//收款对象
    if (isexpamt == true || isexpamt == 'Y') {
        visibleObj = {"start_period": true, "total_period": true }
        disabledObj['start_period'] = false;
        disabledObj['total_period'] = false;

    } else {
        visibleObj = { "start_period": false, "total_period": false };
        disabledObj['start_period'] = false;
        disabledObj['total_period'] = false;
    }
    iscostshare = iscostshare.value
    if (!iscostshare) {
        _this.setState({ hideTables: ['er_cshare_detail'] })
    } else {
        props.form.setFormItemsDisabled("head",{'fydwbm_v':true});
        setImportConfig(_this);//设置导入按钮
        _this.setState({ hideTables: [] })
    }
    org_currinfo = org_currinfo.value;
    if (org_currinfo && parseFloat(org_currinfo.value) == parseFloat(1)) { //业务单据中的币种与组织本币一致时，不可修改
        disabledObj['bbhl'] = true;
    } else {
        disabledObj['bbhl'] = false;
    }
    if(bzbm.value == window.presetVar.zzbwb){//业务单据中的币种与组织本币一致时，汇率及汇率类型不可修改
        disabledObj['zzhllx'] = true;
        disabledObj['bbhl'] = true;
    }

    props.form.setFormItemsVisible(window.presetVar.head.head1, visibleObj);
    props.form.setFormItemsDisabled(window.presetVar.head.head1, disabledObj);

    if(useUpdatePage !== false){
        updatePage(props, 'head', window.presetVar.lsBodys);
    }
    console.timeEnd('billData')

}

//by houyb 20190830 获取控制项
function loadReimsrc(meta, billdata, pagestatus){
    let props = this.props;
    let pageStatus = pagestatus || window.presetVar.pagestatus;
    if (billdata.userjson) {
        billdata.userjson = JSON.stringify({ ...JSON.parse(billdata.userjson), templateid: meta.pageid })
    } else {
        billdata.userjson = JSON.stringify({ templateid: meta.pageid });
    }
    requestApi.loadReimsrc({
        meta: meta,
        props: props,
        data: billdata
    })
}

function initData(meta, billdata, pagestatus) {
    let props = this.props;
    let pageStatus = pagestatus || window.presetVar.pagestatus;
    if (billdata.userjson) {
        billdata.userjson = JSON.stringify({ ...JSON.parse(billdata.userjson), templateid: meta.pageid })
    } else {
        billdata.userjson = JSON.stringify({ templateid: meta.pageid });
    }

    console.timeEnd('meta第1次设置耗时');
    console.time('请求：loadData耗时')
    requestApi.loaddata({
        meta: meta,
        props: props,
        data: billdata,
        success: (data) => {
            beforeUpdatePage(props);
            render.call(this, meta, buttonTpl, pageStatus, false);

            window.presetVar.bodyAllValues = data.bodys
            let addtype = props.getUrlParam('addType');
            // TOP 性能优化，设置默认数据 chengwbc ADD
            props.form.setAllFormValue({ ['head']: data.head['head'] });
            // BTM 性能优化，设置默认数据

            if (addtype == "pull") {
                props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                window.presetVar.reloadHead = data.head[presetVar.head.head1];
                //设置表体数据
                Object.values(presetVar.body).forEach((body) => {
                    if (data.bodys[body]) {
                        props.cardTable.setTableData(body, data.bodys[body]);
                        props.cardTable.setStatus(body, 'edit');
                    }
                });
                //add by heweim 2019/10/18 初始化时触发valueChange
                let bodys = window.presetVar.lsBodys;
                let bodyarr = [];
                let hideTable = this.state.hideTables;
                bodys.map((one)=>{
                    if(hideTable.indexOf(one)<0){
                    bodyarr[bodyarr.length] = one;
                    }
                })
                //申请单 拉单 报销单业务页签编码不能写死，取第一个有数据的业务行页签
                let validBodyArray = [];
                bodyarr.forEach((one)=>{
                   if (excludeBodyKey(one) && data.bodys[one]){
                        let temp = {
                            "tablecode" : one,
                            "tabledata" : data.bodys[one]
                        }
                        validBodyArray.push(temp);
                   }
                })
                if (validBodyArray.length > 0) {
                    let value = '';
                    let moduleid = validBodyArray[0].tablecode;
                    let bodyMoneyArr = props.cardTable.getColValue(moduleid,"vat_amount");
                    for(let i=0;i<bodyMoneyArr.length;i++){
                        if(bodyMoneyArr[i].value!=null||bodyMoneyArr[i].value!=''){
                            value += bodyMoneyArr[i].value;
                        }
                    }
                    let billpulldata = props.createHeadAfterEventData("201102621_2621_IWEB", "head", bodyarr, moduleid, "vat_amount", value);
                    let valueChangeUserjson = { "pagecode": pagecode, "appcode": appcode };
                    valueChangeUserjson["changeRowId"] = props.cardTable.getAllRows(moduleid)[0].rowid;
                    valueChangeUserjson["field"] = "vat_amount";
                    valueChangeUserjson["tableid"] = moduleid;
                    valueChangeUserjson["value"] = value;
                    valueChangeUserjson["oldvalue"] = "";
                    valueChangeUserjson["tradetype"] = props.getUrlParam("tradetype");
                    valueChangeUserjson["uistate"] = pageStatus;
                    billpulldata.card.head["userjson"] = JSON.stringify(valueChangeUserjson);
                    requestApi.valueChange({
                        data: billpulldata.card,
                        success: (data)=> {
                            window.presetVar.bodyAllValues = data.bodys
                            beforeUpdatePage(props);
                            //设置表头数据
                            let filterdata = requestApi.filterDatas(data.head[presetVar.head.head1]);
                            // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                            // props.form.setAllFormValue({[presetVar.head.head1]: filterdata});
                            updataFormData(props, presetVar.head.head1, filterdata);
                            // BTM 性能优化，变更页面数据更新方法
                            window.presetVar.reloadHead = filterdata;
                            //设置表体数据
                            // props.cardTable.setTableData(presetVar.body.body1, data.data.body[presetVar.body.body1]);
                            let filterbodydatas = requestApi.filterDatas(data.bodys[moduleid]);
                            // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                            // props.cardTable.setTableData(moduleid,filterbodydatas);
                            updatacardTableData(props, moduleid, filterbodydatas);
                            // BTM 性能优化，变更页面数据更新方法
                            // let billdatas = props.createExtCardData(window.presetVar.pageId, window.presetVar.head.head1,bodyarr);
                            // requestApi.handleLoadDataResDada(props.meta.getMeta(), {data:billdatas},props,moduleid);
                            props.cardTable.setTableDataWithResetInitValue(moduleid, filterbodydatas);
                            updatePage(props, presetVar.head.head1, [moduleid]);

                        }
                    })
                    //拉单生成的报销单明细需要控制收款对象相关字段的可编辑性
                    validBodyArray.forEach(validBody => {
                        let tablecode = validBody.tablecode;
                        let rows = props.cardTable.getAllRows(tablecode)
                        if (rows){
                            rows.forEach(row => {
                                let currentrow_paytarget = props.cardTable.getValByKeyAndRowId(tablecode, row.rowid, 'paytarget')
                                if (currentrow_paytarget){
                                    let currentrow_paytargetvalue = currentrow_paytarget.value
                                    //控制表体收款对象相关字段的可编辑性
                                    let editablekeys = []
                                    let uneditablekeys = []
                                    if ("0" == currentrow_paytargetvalue){
                                        editablekeys = ['receiver','skyhzh']
                                        uneditablekeys = ['hbbm','hbbm_v','customer','customer_v','custaccount']
                                    }else if("1" == currentrow_paytargetvalue){
                                        editablekeys = ['hbbm','hbbm_v','custaccount']
                                        uneditablekeys = ['receiver','skyhzh','customer','customer_v']
                                    }else if("2" == currentrow_paytargetvalue){
                                        editablekeys = ['customer','customer_v','custaccount']
                                        uneditablekeys = ['receiver','skyhzh','hbbm','hbbm_v']
                                    }
                                    props.cardTable.setEditableByRowId(tablecode, row.rowid, editablekeys, true)
                                    props.cardTable.setEditableByRowId(tablecode, row.rowid, uneditablekeys, false)
                                }
                            })
                        }

                    })

                }
            } else {
                Object.values(presetVar.body).forEach((body) => {
                    if (body !== 'accrued_verify' && body !== 'er_bxcontrast' && body !== 'er_cshare_detail') {
                        // props.cardTable.addRow(body, undefined, undefined, false);
                    }
                });
            }

            dataHandle.call(this, window.presetVar.reloadHead, props, pageStatus);
            setbilldata(this, props, data.head[presetVar.head.head1].rows[0].values);
            props.meta.setMeta(meta);
            //过滤条件延迟添加
            setTimeout(() => {
                setMetasInit(meta, props, data)
                props.meta.setMeta(meta);
            }, 200)

            setTimeout(() => {
                setImportConfigArap(props)
            }, 0)
        }
    });

    props.meta.setMeta(meta);
    // BTM 性能优化，数据返回前增加预先描画模板，提升用户体验
}

function setDefData(meta) {
    return getDefDataFromMeta(meta, 'nc.vo.ep.bx.BXHeaderVO');
}
// TOP 性能优化，保存后不需要setMeta chengwbc MOD
// function render(meta,button,pagestatus) {
function render(meta, button, pagestatus, setMetaFlag) {
    console.time('bizRender')
    // BTM 性能优化，保存后不需要setMeta
    let props = this.props;
    let pageStatus = pagestatus || window.presetVar.pagestatus;
    if (pageStatus == statusVar.add || pageStatus == statusVar.edit) {
        buttonTpl.button.find((btg) => {
            if (btg.key == 'buttongroup2' && btg.children != null) {
                btg.children.find((btn) => {
                    if (btn.key == 'billSubmit') {
                        props.button.setMainButton([pageButton.billSubmit], false);
                        btn['title'] = this.multiLangJson['2011-0019'];//"保存提交"
                        return true;
                    }
                })
                return true;
            }
        })
    } else {
        buttonTpl.button.find((btg) => {
            if (btg.key == 'buttongroup2' && btg.children != null) {
                btg.children.find((btn) => {
                    if (btn.key == 'billSubmit') {
                        props.button.setMainButton([pageButton.billSubmit], true);
                        btn['title'] = this.multiLangJson['2011-0014'];//"提交"
                        return true;
                    }
                })
                return true;
            }
        })
    }
    renderButtions.call(this, props, meta, pageButton, pageStatus);

    if (setMetaFlag) {
        props.meta.setMeta(meta);
    }
    // BTM 性能优化，保存后不需要setMeta
    console.timeEnd('bizRender')
}
export { render }
function renderButtions(props, meta, pageButton, pagestatus) {
    //肩部按钮可见状态：页面和表格的肩部按钮，这里逻辑根据实际业务实现。
    let btnsVisibleObj = {};
    for (let btnKey in pageButton) {
        btnsVisibleObj[btnKey] = false;
    }
    let pageStatus = pagestatus || window.presetVar.pagestatus;
    let isAddOrEditStatus = pageStatus == statusVar.edit || pageStatus == statusVar.add;
    let isBrowseStatus = pageStatus == statusVar.browse;
    switch (pageStatus) {
        case statusVar.edit:
        case statusVar.add:
            {
                setPageStatus(props, meta, ['head'], window.presetVar.lsBodys, pageStatus);
                props.cardTable.setStatus('er_bxcontrast', window.presetVar.status.browse);//冲销页签不允许直接修改
            }
            // BTM 整体设置页面状态
            break;
        case statusVar.browse:
            {
                setPageStatus(props, meta, ['head'], window.presetVar.lsBodys, 'browse');
            }
            // BTM 整体设置页面状态
            break;
    }
    window.presetVar.buttonTpl.button.map((one) => {
        if (one.area.indexOf('card_body') > -1 && isBrowseStatus) {
            //browse状态下可联查附件
            if (!(one.area.indexOf('card_body_inner') > -1 && one.key.indexOf('_Edit') > -1 || one.key.indexOf('_Attachment') > -1)) {
                btnsVisibleObj[one.key] = false;
            }
            // 放开查看发票、查看明细按钮
            if(one.area.indexOf('card_body_inner') > -1 && one.key.indexOf('invoice_') > -1){
                btnsVisibleObj[one.key] = true;
            }
        }
        if (one.area.indexOf('card_body') > -1 && isAddOrEditStatus) {
            if (!(one.area.indexOf('card_body_inner') > -1 && one.key.indexOf('_Edit') > -1)) {
                btnsVisibleObj[one.key] = true;
            }
        }
    });
    // props.button.setButtonsVisible(btnsVisibleObj);
    setButtonsVisible(props, btnsVisibleObj);
}
export { renderButtions }
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return "";
}
export { getCookie }
// 1903方式，参数列表在url中，改为根据url的page属性从session中获取
// function getRequest1(url) {
//     if (!url)
//         url = document.location.search;
//     var theRequest = new Object();
//     if (url.indexOf("?") != -1) {
//         var str = url.substring(url.indexOf("?") + 1);
//         var strs = str.split("&");
//         for (var i = 0; i < strs.length; i++) {
//             theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
//         }
//     }
//     return theRequest;
// }
// xuzd5 适配到1909
function getRequest1(url) {
    if (!url)
        url = document.location.search;
    let sessionInfo = ""
    if (url.indexOf("page=") != -1) {
        //获取url中页面page参数 1909url中参数仅有page
        var page;
        if (url.indexOf("?") != -1) {
            var str = url.substring(url.indexOf("?") + 1);
            var strs = str.split("&");
            page = strs[0].split("=")[1];
        }

        //根据page获取session storage中原来1903url中的参数
        var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
        msg = JSON.parse(msg);
        sessionInfo = msg[page];
    } else if (url.indexOf("?") != -1) {
        sessionInfo = url.substring(url.indexOf("?") + 1);
    } else {
        sessionInfo = url;
    }


    //解析参数
    var theRequest = new Object();
    var strs = sessionInfo.split("&");
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
}
export { getRequest1 }
function getRequestString(name) {
    if (getRequest1()[name] != undefined) {
        return getRequest1()[name];
    }
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
function dataHandle(head, props, pagestatus) {
    const that = this;
    //处理数据和按钮状态
    if(!head) return
    if (head == null || head.rows[0] == null || head.rows[0].values == null)
        head = props.form.getAllFormValue("head");
    let sxbz = head.rows[0].values.sxbz.value;//单据生效状态
    let spzt = head.rows[0].values.spzt.value;//审批状态
    let djzt = head.rows[0].values.djzt.value//单据状态
    const creator = head.rows[0].values.creator.value
    const operator = head.rows[0].values.operator.value
    let iscostshare = head.rows[0].values.iscostshare.value == null || head.rows[0].values.iscostshare.value == undefined ? false : head.rows[0].values.iscostshare.value;
    let btnsVisibleObj = {};
    let pageStatus = pagestatus || window.presetVar.pagestatus;
    let isAddOrEditStatus = pageStatus == statusVar.edit || pageStatus == statusVar.add;
    let isBrowseStatus = pageStatus == statusVar.browse;
    renderButtions.call(this, props, props.meta.getMeta(), window.presetVar.buttonTpl.button, pageStatus);
    let scene = props.getUrlParam('scene');//第三方打开
    let deal = props.getUrlParam('deal');
    if (isAddOrEditStatus) {
        btnsVisibleObj["pageEdit"] = false;//修改--组buttongroup1
        btnsVisibleObj["pageCopy"] = false;//复制--组buttongroup1
        btnsVisibleObj["pageDel"] = false;//删除 --组buttongroup1
        btnsVisibleObj["billRecall"] = false;//收回 --组buttongroup2
        btnsVisibleObj["pageSave"] = true;//保存 --组buttongroup2
        //审批人门户和作业任务处理修改单据无提交按钮
        if (scene == 'approve' || scene == 'approvesce' || scene == 'zycl') {
            btnsVisibleObj["billSubmit"] = false;//提交 --组buttongroup2
        } else {
            btnsVisibleObj["billSubmit"] = true;//提交 --组buttongroup2
        }
        btnsVisibleObj["buttongroup2"] = true;
        btnsVisibleObj["imageUpload"] = false;//影像扫描 --组buttongroup3
        btnsVisibleObj["imageShow"] = false;//影像查看 --组buttongroup3
        //buttongroup6更多
        //buttongroup6-c联查
        //buttongroup6-o其他
        btnsVisibleObj["invoiceView"] = false;//联查发票buttongroup6-c
        btnsVisibleObj["linkQueryFysq"] = false;//联查费用申请单 --组buttongroup6-c
        btnsVisibleObj["linkQueryFyyt"] = false;//联查费用预提单 --组buttongroup6-c
        btnsVisibleObj["linkQueryJkbx"] = false;//联查借款单 --组buttongroup6-c
        btnsVisibleObj["billApprove"] = false;//联查审批情况 --组buttongroup6-c
        btnsVisibleObj["buttongroup6-c"] = false;//编辑态联查组不显示
        btnsVisibleObj["pagePrint"] = false;//打印  --组buttongroup6-o
        btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
        btnsVisibleObj["billInvalid"] = false;//作废--组buttongroup6-o
        btnsVisibleObj["buttongroup6-o"] = false;//编辑态其他组不显示
        btnsVisibleObj["buttongroup6"] = false;//编辑态更多不显示
        btnsVisibleObj["pageClose"] = true;//取消 编辑态显示取消
        btnsVisibleObj["pageCjk"] = true;//冲借款
        btnsVisibleObj["pageWallet"] = true;//票夹
        btnsVisibleObj["pageFyyt"] = true;//核销预提
        btnsVisibleObj["fileManager"] = true;//附件
        btnsVisibleObj["LinkBudget"] = false;//联查预算
        btnsVisibleObj["LinkVoucher"] = false;//联查凭证
        btnsVisibleObj["scan_invoice_btn"] = true;//扫描发票
        btnsVisibleObj["local_invoice_btn"] = true;//本地上传
    } else {
        if(djzt == "-1") {//作废
            for (let btnKey in pageButton) {
                if ( btnKey == pageButton.pageCopy || btnKey == pageButton.imageShow || btnKey == pageButton.pagePrint) {
                    btnsVisibleObj[btnKey] = true;
                } else {
                    btnsVisibleObj[btnKey] = false;
                }

            }
        }else if ((scene == null || scene == undefined || scene == 'bz')) {//制单页面，报账进度查询
            //单据未提交
            if (spzt == -1 || spzt == null || spzt == 0) {
                btnsVisibleObj["pageEdit"] = true;//修改--组buttongroup1
                btnsVisibleObj["pageDel"] = true;//删除 --组buttongroup1
                btnsVisibleObj["billSubmit"] = true;//提交 --组buttongroup2
                btnsVisibleObj["billInvalid"] = true;//作废--组buttongroup6-o
                btnsVisibleObj["LinkVoucher"] = false;//联查凭证
                btnsVisibleObj["imageUpload"] = true;//影像扫描 --组buttongroup3
            } else {
                //单据已经提交
                btnsVisibleObj["pageEdit"] = false;//修改--组buttongroup1
                btnsVisibleObj["pageDel"] = false;//删除 --组buttongroup1
                btnsVisibleObj["billSubmit"] = false;//提交 --组buttongroup2
                btnsVisibleObj["billInvalid"] = false;//作废--组buttongroup6-o
                btnsVisibleObj["LinkVoucher"] = true;//联查凭证
            }
            btnsVisibleObj["pageCopy"] = true;//复制--组buttongroup1
            if (spzt == -1 || spzt == 0 || spzt == null || spzt == 1) {
                btnsVisibleObj["billRecall"] = false;//收回 --组buttongroup2
            } else {
                btnsVisibleObj["billRecall"] = true;//收回 --组buttongroup2
            }
            //审批通过后隐藏电子发票按钮
            if (spzt == 1) {
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
                that&&that.setState({uploaderBtnDisable: true})
            } else {
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
            }
            btnsVisibleObj["pageSave"] = false;//保存 --组buttongroup2
            btnsVisibleObj["imageShow"] = true;//影像查看 --组buttongroup3
            //buttongroup6更多
            //buttongroup6-c联查
            //buttongroup6-o其他
            btnsVisibleObj["invoiceView"] = false;//联查发票buttongroup6-c
            btnsVisibleObj["linkQueryFysq"] = true;//联查费用申请单 --组buttongroup6-c
            btnsVisibleObj["linkQueryFyyt"] = true;//联查费用预提单 --组buttongroup6-c
            btnsVisibleObj["linkQueryJkbx"] = true;//联查借款单 --组buttongroup6-c
            btnsVisibleObj["billApprove"] = true;//联查审批情况 --组buttongroup6-c
            btnsVisibleObj["buttongroup6-c"] = true;//编辑态联查组不显示
            btnsVisibleObj["pagePrint"] = true;//打印  --组buttongroup6-o
            // btnsVisibleObj["invoiceDzfp"] = true;//电子发票--组buttongroup6-o
            btnsVisibleObj["buttongroup6-o"] = true;//其他组显示
            btnsVisibleObj["buttongroup6"] = true;//更多显示
            btnsVisibleObj["pageClose"] = false;//取消 显示
            btnsVisibleObj["pageCjk"] = false;//冲借款
            btnsVisibleObj["pageFyyt"] = false;//核销预提
            btnsVisibleObj["fileManager"] = true;//附件
            btnsVisibleObj["LinkBudget"] = false;//联查预算
            btnsVisibleObj["LinkVoucher"] = false;//联查凭证
            btnsVisibleObj["pageWallet"] = false;// 票夹
            btnsVisibleObj["local_invoice_btn"] = false;// 发票上传
        }
        //审批人门户和作业任务处理
        else if ((scene == 'approve' || scene == 'approvesce' || scene == 'zycl' || scene == 'approvesce')) {
            if (spzt != 1) {
                btnsVisibleObj["pageEdit"] = true;//修改--组buttongroup1
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
                btnsVisibleObj["imageUpload"] = true;//影像扫描 --组buttongroup3
            } else {
                btnsVisibleObj["pageEdit"] = false;//修改--组buttongroup1
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
                btnsVisibleObj["pageMakebill"] = true;//审批中心的制单按钮
            }
            btnsVisibleObj["pageCopy"] = false;//复制--组buttongroup1
            btnsVisibleObj["pageDel"] = false;//删除 --组buttongroup1
            btnsVisibleObj["billRecall"] = false;//收回 --组buttongroup2
            btnsVisibleObj["pageSave"] = false;//保存 --组buttongroup2
            btnsVisibleObj["billSubmit"] = false;//提交 --组buttongroup2
            btnsVisibleObj["buttongroup2"] = false;
            // btnsVisibleObj["imageUpload"] = false;//影像扫描 --组buttongroup3
            btnsVisibleObj["imageShow"] = true;//影像查看 --组buttongroup3
            //buttongroup6更多
            //buttongroup6-c联查
            //buttongroup6-o其他
            btnsVisibleObj["invoiceView"] = false;//联查发票buttongroup6-c
            btnsVisibleObj["linkQueryFysq"] = true;//联查费用申请单 --组buttongroup6-c
            btnsVisibleObj["linkQueryFyyt"] = true;//联查费用预提单 --组buttongroup6-c
            btnsVisibleObj["linkQueryJkbx"] = true;//联查借款单 --组buttongroup6-c
            btnsVisibleObj["billApprove"] = true;//联查审批情况 --组buttongroup6-c
            btnsVisibleObj["buttongroup6-c"] = true;//编辑态联查组不显示
            btnsVisibleObj["pagePrint"] = true;//打印  --组buttongroup6-o
            // btnsVisibleObj["invoiceDzfp"] = true;//电子发票--组buttongroup6-o
            btnsVisibleObj["billInvalid"] = false;//作废--组buttongroup6-o
            btnsVisibleObj["buttongroup6-o"] = true;//编辑态其他组不显示
            btnsVisibleObj["buttongroup6"] = true;//编辑态更多不显示
            btnsVisibleObj["pageClose"] = false;//取消 编辑态显示取消
            btnsVisibleObj["pageCjk"] = false;//冲借款
            btnsVisibleObj["pageFyyt"] = false;//核销预提
            btnsVisibleObj["fileManager"] = true;//附件
            btnsVisibleObj["LinkBudget"] = true;//联查预算
            btnsVisibleObj["LinkVoucher"] = true;//联查凭证
            if(spzt == '1') {
                that&&that.setState({uploaderBtnDisable: true})
            }
        } //报账单据查询只显示联查相关信息
        else if (scene == 'bzcx' || scene == 'lc' ) {
            if (spzt == 1) {
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
                that&&that.setState({uploaderBtnDisable: true})
            } else {
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
            }
            btnsVisibleObj["pageEdit"] = false;//修改--组buttongroup1
            btnsVisibleObj["pageCopy"] = false;//复制--组buttongroup1
            btnsVisibleObj["pageDel"] = false;//删除 --组buttongroup1
            btnsVisibleObj["billRecall"] = false;//收回 --组buttongroup2
            btnsVisibleObj["pageSave"] = false;//保存 --组buttongroup2
            btnsVisibleObj["billSubmit"] = false;//提交 --组buttongroup2
            btnsVisibleObj["buttongroup2"] = false;
            btnsVisibleObj["imageUpload"] = false;//影像扫描 --组buttongroup3
            btnsVisibleObj["imageShow"] = true;//影像查看 --组buttongroup3
            //buttongroup6更多
            //buttongroup6-c联查
            //buttongroup6-o其他
            btnsVisibleObj["invoiceView"] = false;//联查发票buttongroup6-c
            btnsVisibleObj["linkQueryFysq"] = true;//联查费用申请单 --组buttongroup6-c
            btnsVisibleObj["linkQueryFyyt"] = true;//联查费用预提单 --组buttongroup6-c
            btnsVisibleObj["linkQueryJkbx"] = true;//联查借款单 --组buttongroup6-c
            btnsVisibleObj["billApprove"] = true;//联查审批情况 --组buttongroup6-c
            btnsVisibleObj["buttongroup6-c"] = true;//编辑态联查组不显示
            btnsVisibleObj["pagePrint"] = true;//打印  --组buttongroup6-o
            // btnsVisibleObj["invoiceDzfp"] = true;//电子发票--组buttongroup6-o
            btnsVisibleObj["billInvalid"] = false;//作废--组buttongroup6-o
            btnsVisibleObj["buttongroup6-o"] = true;//编辑态其他组不显示
            btnsVisibleObj["buttongroup6"] = true;//编辑态更多不显示
            btnsVisibleObj["pageClose"] = false;//取消 编辑态显示取消
            btnsVisibleObj["pageCjk"] = false;//冲借款
            btnsVisibleObj["pageFyyt"] = false;//核销预提
            btnsVisibleObj["fileManager"] = true;//附件
            if (spzt == -1){
                btnsVisibleObj["LinkBudget"] = false;//联查预算
            }else{
                btnsVisibleObj["LinkBudget"] = true;//联查预算
            }
            btnsVisibleObj["LinkVoucher"] = true;//联查凭证

        }
        //费用报销查询，作业管理 只显示联查相关信息
        else if (scene == 'fycx' || scene == 'zycx') {
            if (spzt == 1) {
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
                that && that.setState({uploaderBtnDisable: true})
            } else {
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
            }
            btnsVisibleObj["pageEdit"] = false;//修改--组buttongroup1
            btnsVisibleObj["pageCopy"] = false;//复制--组buttongroup1
            btnsVisibleObj["pageDel"] = false;//删除 --组buttongroup1
            btnsVisibleObj["billRecall"] = false;//收回 --组buttongroup2
            btnsVisibleObj["pageSave"] = false;//保存 --组buttongroup2
            btnsVisibleObj["billSubmit"] = false;//提交 --组buttongroup2
            btnsVisibleObj["buttongroup2"] = false;
            btnsVisibleObj["imageUpload"] = false;//影像扫描 --组buttongroup3
            btnsVisibleObj["imageShow"] = true;//影像查看 --组buttongroup3
            //buttongroup6更多
            //buttongroup6-c联查
            //buttongroup6-o其他
            btnsVisibleObj["invoiceView"] = false;//联查发票buttongroup6-c
            btnsVisibleObj["linkQueryFysq"] = true;//联查费用申请单 --组buttongroup6-c
            btnsVisibleObj["linkQueryFyyt"] = true;//联查费用预提单 --组buttongroup6-c
            btnsVisibleObj["linkQueryJkbx"] = true;//联查借款单 --组buttongroup6-c
            btnsVisibleObj["billApprove"] = true;//联查审批情况 --组buttongroup6-c
            btnsVisibleObj["buttongroup6-c"] = true;//编辑态联查组不显示
            btnsVisibleObj["pagePrint"] = true;//打印  --组buttongroup6-o
            // btnsVisibleObj["invoiceDzfp"] = true;//电子发票--组buttongroup6-o
            btnsVisibleObj["billInvalid"] = false;//作废--组buttongroup6-o
            btnsVisibleObj["buttongroup6-o"] = true;//编辑态其他组不显示
            btnsVisibleObj["buttongroup6"] = true;//编辑态更多不显示
            btnsVisibleObj["pageClose"] = false;//取消 编辑态显示取消
            btnsVisibleObj["pageCjk"] = false;//冲借款
            btnsVisibleObj["pageFyyt"] = false;//核销预提
            btnsVisibleObj["fileManager"] = true;//附件
            btnsVisibleObj["LinkBudget"] = true;//联查预算
            btnsVisibleObj["LinkVoucher"] = true;//联查凭证
        } //消息中心打开单据
        else if (scene == 'notice') {
            if (spzt == 1) {
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
            } else {
                btnsVisibleObj["invoiceDzfp"] = false;//电子发票--组buttongroup6-o
            }
            btnsVisibleObj["pageEdit"] = false;//修改--组buttongroup1
            btnsVisibleObj["pageCopy"] = false;//复制--组buttongroup1
            btnsVisibleObj["pageDel"] = false;//删除 --组buttongroup1
            btnsVisibleObj["billRecall"] = false;//收回 --组buttongroup2
            btnsVisibleObj["pageSave"] = false;//保存 --组buttongroup2
            btnsVisibleObj["billSubmit"] = false;//提交 --组buttongroup2
            btnsVisibleObj["buttongroup2"] = false;
            btnsVisibleObj["imageUpload"] = false;//影像扫描 --组buttongroup3
            btnsVisibleObj["imageShow"] = false;//影像查看 --组buttongroup3
            //buttongroup6更多
            //buttongroup6-c联查
            //buttongroup6-o其他
            btnsVisibleObj["invoiceView"] = false;//联查发票buttongroup6-c
            btnsVisibleObj["linkQueryFysq"] = false;//联查费用申请单 --组buttongroup6-c
            btnsVisibleObj["linkQueryFyyt"] = false;//联查费用预提单 --组buttongroup6-c
            btnsVisibleObj["linkQueryJkbx"] = false;//联查借款单 --组buttongroup6-c
            btnsVisibleObj["billApprove"] = true;//联查审批情况 --组buttongroup6-c
            btnsVisibleObj["buttongroup6-c"] = false;//编辑态联查组不显示
            btnsVisibleObj["pagePrint"] = false;//打印  --组buttongroup6-o
            // btnsVisibleObj["invoiceDzfp"] = true;//电子发票--组buttongroup6-o
            btnsVisibleObj["billInvalid"] = false;//作废--组buttongroup6-o
            btnsVisibleObj["buttongroup6-o"] = false;//编辑态其他组不显示
            btnsVisibleObj["buttongroup6"] = false;//编辑态更多不显示
            btnsVisibleObj["pageClose"] = false;//取消 编辑态显示取消
            btnsVisibleObj["pageCjk"] = false;//冲借款
            btnsVisibleObj["pageFyyt"] = false;//核销预提
            btnsVisibleObj["fileManager"] = false;//附件
            btnsVisibleObj["LinkBudget"] = false;//联查预算
            btnsVisibleObj["LinkVoucher"] = false;//联查凭证
        }

    }
    if (deal != undefined && (deal == 'handon' || deal == 'adjust' || deal == 'sscreject' || deal == 'handled')) {
        btnsVisibleObj["pageEdit"] = false;
    }
    btnsVisibleObj['qry_loan'] = true
    //来源于报表联查的单据, 结算节点联查的单据
    if (scene == 'sscermlink' || scene == "linksce") {
        btnsVisibleObj["invoiceView"] = false;//联查发票buttongroup6-c
        btnsVisibleObj["linkQueryFysq"] = true;//联查费用申请单 --组buttongroup6-c
        btnsVisibleObj["linkQueryFyyt"] = true;//联查费用预提单 --组buttongroup6-c
        btnsVisibleObj["linkQueryJkbx"] = true;//联查借款单 --组buttongroup6-c
        btnsVisibleObj["buttongroup6-c"] = true;//编辑态联查组不显示
        btnsVisibleObj["pagePrint"] = true;//打印  --组buttongroup6-o
        btnsVisibleObj["fileManager"] = true;//附件
        btnsVisibleObj["LinkBudget"] = true;//联查预算
        btnsVisibleObj["LinkVoucher"] = true;//联查凭证
        btnsVisibleObj["imageShow"] = true; // 影像查看
        btnsVisibleObj["billApprove"] = true;//联查审批情况 --组buttongroup6-c
        if (spzt == 1) that && that.setState({uploaderBtnDisable: true})
    }
    if(scene =='bzcx') {
        btnsVisibleObj['qry_loan'] = false  //暂时处理,联查不显示借款情况
        if( djzt == '-1' ) {
            btnsVisibleObj[pageButton.pageCopy] = false
        }
    }
    // 审批进行中  提交状态 附件可编辑受控
    if (spzt == 2 || spzt == 3) {
        if (window.presetVar.attachmentControl) {
            that && that.setState({uploaderBtnDisable: !window.presetVar.attachmentControl.modify})
        }
    } else if(spzt == -1) {
        //单据不在审批中,默认可修改
        that && that.setState({uploaderBtnDisable: false})
    }
    
    setButtonsVisible(props, btnsVisibleObj);
}
export { dataHandle }
//路由变化监听函数，location.hash及linkTo,pushTo都会调用
function routeChange(props) {
    let pageStatus = props.getUrlParam('status');
    window.presetVar.pagestatus = pageStatus;
    let meta = props.meta.getMeta();
    loadbill.call(this, meta, pageStatus);
}
export { routeChange }

/**
 *
 * @param {处理表体增行后的默认值} tablecode
 */
function setDefautValueAfterBodyAdd(props, tablecode, index, inInsert) {
    const moudleid = tablecode;
    const multiLang = props.MutiInit.getIntl(2011);

    //rowIndex不能使用getAllRows,要使用getVisibleRows,前者会带出删除的行,在删除行再新增的情况下，rowIndex计算错误
    let rowIndex = index || 0;
    let rowValues = props.cardTable.getDataByIndex(moudleid, rowIndex).values;

    if (
        rowValues.pk_item &&
        rowValues.pk_item.value &&
        rowValues.pk_mtapp_detail &&
        rowValues.pk_mtapp_detail.value
    ) {
        let clickedIndex = 0
        if (index == null) {
            clickedIndex = 0;
        } else {
            clickedIndex = index;
        }
		if (inInsert) {
			rowIndex = index + 1;
		} else {
			rowIndex= props.cardTable.getVisibleRows(moudleid).length - 1;
		}
        rowValues = _.cloneDeep(props.cardTable.getDataByIndex(moudleid, clickedIndex).values);
        _.forOwn(rowValues, function (value, key) {
            if (
                [
                    'cjkybje',
                    'cjkbbje',
                    'zfybje',
                    'zfbbje',
                    'hkybje',
                    'hkbbje',
                    'ybje',
                    'bbje',
                    'total',
                    'ybye',
                    'bbye',
                    'globalcjkbbje',
                    'globalzfbbje',
                    'globalhkbbje',
                    'globalbbje',
                    'globalbbye',
                    'groupcjkbbje',
                    'groupzfbbje',
                    'grouphkbbje',
                    'groupbbje',
                    'groupbbye',
                    'tax_amount',
                    'vat_amount',
                    'tni_amount',
                    'orgtax_amount',
                    'orgvat_amount',
                    'orgtni_amount',
                    'grouptax_amount',
                    'groupvat_amount',
                    'grouptni_amount',
                    'globaltax_amount',
                    'globalvat_amount',
                    'globaltni_amount',
                    'inputtax',
                    'fpdm',
                    'fphm',
                    'fplxpk',
                    'amount',
                    'pk_erminvoice',
                    'pk_erminvoice_b',
                    'generatetype',
                    'autograph'
                ].includes(key)
            ) {
                rowValues[key] = {};
            }
        });
        props.cardTable.setValByKeysAndIndex(moudleid, rowIndex, rowValues);
        // props.cardTable.setValByKeyAndIndex(moudleid, rowIndex, 'pk_item', rowValues.pk_item);
        // props.cardTable.setValByKeyAndIndex(moudleid, rowIndex, 'pk_mtapp_detail', rowValues.pk_mtapp_detail);
    } else {
        rowIndex= props.cardTable.getVisibleRows(moudleid).length - 1;
        rowValues = props.cardTable.getDataByIndex(moudleid, rowIndex).values;
    }

    props.cardTable.focusRowByIndex(moudleid, rowIndex);
    //新增行，如果有带的默认数据，先清空默认数据
    const moduleTem = props.meta.getMeta();
    const itm_keys = [];
    moduleTem[moudleid] &&
        moduleTem[moudleid].items.forEach((itm) => {
            if (itm.attrcode && itm.attrcode !== 'pk_item' && itm.attrcode !== 'pk_mtapp_detail' && !itm.initialvalue) {
                itm_keys.push(itm.attrcode);
            }
        });
    let origin = {}
    for (let key of itm_keys) {
        const val = rowValues[key];
        if (val && (val.display || val.scale || val.value)) {
                origin[key] = {display: null, value : null}
        }
    }

    props.cardTable.setValByKeysAndIndex(moudleid, rowIndex, origin)
    clearPropsAboutInvoices.call(this, moudleid, rowIndex)


    //补充一些默认值的逻辑，修改单据时，新增别的页签没有默认值，新增组织汇率类型，组织汇率来源日期
    let keys = ['bzbm','dwbm','deptid','jkbxr','paytarget','receiver','skyhzh','hbbm','customer','hbbm_v','customer_v','custaccount','bbhl','groupbbhl','globalbbhl','zzhllx','zzhllyrq']
    let default_values = {}
    keys.forEach(key => {
        let headvalue = props.form.getFormItemsValue(window.presetVar.head.head1,key);
        default_values[key] = headvalue
    })
    props.cardTable.setValByKeysAndIndex(moudleid, rowIndex, default_values)

    let paytarget = props.cardTable.getDataByIndex(moudleid, rowIndex).values['paytarget'].value
    let nullvalue = {
        display: null,
        value : null
    }

    // 增行时，本币汇率、汇率类型、汇率来源日期，需根据表头来设置表体其编辑性
    let bbhlFlag = props.form.getFormItemsDisabled('head', 'bbhl'); //表头本币汇率编辑性
    let zzhllxFlag = props.form.getFormItemsDisabled('head', 'zzhllx'); //表头本币汇率类型编辑性
    let zzhllyrqFlag = props.form.getFormItemsDisabled('head', 'zzhllyrq'); //表头本币汇率日期编辑性
    // 表头中本币种、汇率类型更改后，表体中本币汇率、汇率类型、汇率来源日期需同时控制其编辑性
    let editkeys = []
    let unedikeys = []
    bbhlFlag ? unedikeys.push('bbhl') : editkeys.push('bbhl')
    zzhllxFlag ? unedikeys.push('zzhllx') : editkeys.push('zzhllx')
    zzhllyrqFlag ? unedikeys.push('zzhllyrq') : editkeys.push('zzhllyrq')
    props.cardTable.setEditableByIndex(moudleid, rowIndex, editkeys, true)
    props.cardTable.setEditableByIndex(moudleid, rowIndex, unedikeys, false)

    //新增行时，清理掉与收款对象不匹配的其他字段的默认值
    if (paytarget == '0'){
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'hbbm',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'customer',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'custaccount',nullvalue)
        props.cardTable.setEditableByIndex(moudleid, [rowIndex], ['hbbm','hbbm_v','customer','customer_v','custaccount'], false)
    }else if (paytarget == '1'){
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'receiver',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'customer',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'skyhzh',nullvalue)
        props.cardTable.setEditableByIndex(moudleid, [rowIndex], ['receiver','customer','customer_v','skyhzh'], false)
    }else if (paytarget == '2'){
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'receiver',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'hbbm',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'skyhzh',nullvalue)
        props.cardTable.setEditableByIndex(moudleid, [rowIndex], ['receiver','hbbm','hbbm_v','skyhzh'], false)
    }
}

function setImportConfigArap(props){
    let tabledata = [];
    let formdata = props.createExtCardData(props.meta.getMeta().pageid, "head", ['arap_bxbusitem']);
    props.meta.getMeta().arap_bxbusitem.items.forEach((item) =>{
        if(item.attrcode !="opr"){
            tabledata.push({"visible":item.visible,"key":item.attrcode,"label":item.label,"itemtype":item.itemtype,"initialvalue":item.initialvalue && item.initialvalue.value?item.initialvalue.value:""});
        }
    });
    formdata.userjson = JSON.stringify(tabledata);
    let config = getExcelImportConfig('/nccloud/erm/expenseaccount/ExpenseaccountBusitemImportAction.do',formdata,(resultinfo)=>{
        if (resultinfo == 'beginUpload') {

        } else if (resultinfo.success) {
            let exceldata = resultinfo.data.bodys.arap_bxbusitem;
            props.cardTable.setTableData('arap_bxbusitem',  exceldata);

            //计算含税金额
            let vat_amount_total = 0;
            let zfbbje_total = 0;
            exceldata.rows.forEach(row => {
                if(row.values.vat_amount) {
                    vat_amount_total += row.values.vat_amount.value
                }
                if(row.values.zfbbje) {
                    zfbbje_total += row.values.zfbbje.value
                }
            })
            resultinfo.data.head['head'].rows[0].values['vat_amount'].value = vat_amount_total
            resultinfo.data.head['head'].rows[0].values['zfbbje'].value =  vat_amount_total  //如果表体
            //没有放出来本币支付金额，默认用含税金额
            updataFormData(props, 'head', resultinfo.data.head['head']);

            toast({content: `已成功导入${resultinfo.data.bodys.arap_bxbusitem.rows.length}条`, color: 'success'})

        }
    });

    props.button.setUploadConfig('arap_bxbusitem_file', config);
}

export { setDefautValueAfterBodyAdd }
